<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/4/4
 * Time: 22:38
 */

namespace app\index\logic;


use app\admin\logic\MoneyLogic;
use app\common\utils\Constant;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;
use think\Log;

class AnswerLogic
{
    /**
     * 创建答题记录
     * @param $red_envelope_id int 红包id
     * @param $user_id int 用户id
     * @return array
     */
    public function doCreateAnswerLog($red_envelope_id,$user_id){
        Db::startTrans();
        try{
            $red_envelope = model('RedEnvelope')->where(array('id'=>$red_envelope_id))->find();
            if(!$red_envelope){
                return array('status'=>2,'msg'=>'请勿非法提交');
            }
            if($red_envelope['status'] != Constant::RED_ENVELOPE_STATUS_NO_CHALLENGE || $red_envelope['is_pay'] != 1){
                return array('status'=>2,'msg'=>'对不起，当前挑战无法答题！');
            }
            if($red_envelope['user_id'] == $user_id) {
                return array('status' => 2, 'msg' => '对不起，您无法答题！');
            }
            $success = $this->checkChallenges($user_id);
            if($success){
                return array('status' => 2, 'msg' => '啊哦！防沉迷系统报告有异常，请联系客服处理。');
            }
            $answer_money = model('User')->where(array('id'=>$user_id))->value('answer_money');
            if($answer_money < $red_envelope['answer_money']){
                //在线支付
                $result = $this->createAnswerLogAndOrder($red_envelope,$user_id);
                if($result['status'] != 1){
                    Db::rollback();
                    return $result;
                }
            }else{
                //直接支付
                $this->rewardAnswer($user_id);//判断是否首次答题
                $this->payByAnswerMoney($user_id,$red_envelope['answer_money'],$red_envelope_id);
                $topic_ids = $this->getRandomTopicByGrade($red_envelope['topic_grade'],$red_envelope['topic_number']);
                $topic_ids_array = explode(',',$topic_ids);
                if(empty($topic_ids) || count($topic_ids_array) < $red_envelope['topic_number']){
                    Db::rollback();
                    return array('status'=>2,'msg'=>'答题失败');
                }
                $pay_type = Constant::ORDER_PAY_TYPE_WE_CHAT;
                $answer_log_id = $this->createAnswerLog($red_envelope,$user_id,$pay_type,$topic_ids,1);
                $data['answer_log_id'] = $answer_log_id;
                $data['is_need_pay'] = false;
                $data['money'] = $red_envelope['answer_money'];
                $result = array('status'=>1,'data'=>$data);
            }
            Db::commit();
            return $result;
        }catch (Exception $e){
            Db::rollback();
            return array('status'=>0,'error'=>$e->getMessage());
        }
    }

    private function getAnswerLogCount($user_id){
        $map['user_id'] = $user_id;
        $map['is_all_right'] = 1;
        $map['status'] = Constant::ANSWER_STATUS_END;
        $begin_time=date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y')));
        $end_time=date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1);
        $count = model('AnswerLog')
            ->where($map)
            ->whereTime('create_time', 'between', [$begin_time, $end_time])
            ->count();
        return $count;
    }

    private function checkChallenges($user_id){
        $count = $this->getAnswerLogCount($user_id);
        $limit = model('Config')->where(array('name'=>Constant::CONFIG_NAME_CHALLENGE_NUMBER))->value('value');
        return $count >= $limit;
    }

    /**
     * 挑战卡支付答题金
     * @param $user_id
     * @param $answer_money
     * @param $red_envelope_id int 红包id
     */
    private function payByAnswerMoney($user_id,$answer_money,$red_envelope_id){
        //修改为正在挑战中
        model('RedEnvelope')->where(array('id'=>$red_envelope_id))->setField('status',Constant::RED_ENVELOPE_STATUS_IN_THE_CHALLENGE);
        model('User')->where(array('id'=>$user_id))->setDec('answer_money',$answer_money);
        $current_money = model('User')->where(array('id'=>$user_id))->value('answer_money');
        $logic = new MoneyLogic();
        $change_type = Constant::CHANGE_TYPE_PAY_ANSWER;
        $in_out_type = Constant::IN_OUT_TYPE_OUT;
        $money_type = Constant::MONEY_TYPE_CHALLENGE_CARD;
        $desc = '使用挑战卡答题';
        $logic->saveMoneyLog($answer_money,$current_money,$change_type,
            $in_out_type,$desc,$user_id,$money_type,0);
        $message_logic = new MessageLogic();
        $send_user_id = model('RedEnvelope')->where(array('id'=>$red_envelope_id))->value('user_id');
        $message_logic->sendMessage($send_user_id,Constant::CONFIG_NAME_ANSWER_NOTICE);
        //答题金进入红包发送者账户
        $this->returnMoneyToSender($red_envelope_id,$user_id);
    }

    /**
     * 创建订单和答题记录 需要支付
     * @param $red_envelope
     * @param $user_id
     * @return array
     */
    private function createAnswerLogAndOrder($red_envelope,$user_id){
        $topic_ids = $this->getRandomTopicByGrade($red_envelope['topic_grade'],$red_envelope['topic_number']);
        $topic_ids_array = explode(',',$topic_ids);
        if(empty($topic_ids) || count($topic_ids_array) < $red_envelope['topic_number']){
            return array('status'=>2,'msg'=>'答题失败！');
        }
        $pay_type = Constant::ORDER_PAY_TYPE_WE_CHAT;
        $answer_log_id = $this->createAnswerLog($red_envelope,$user_id,$pay_type,$topic_ids,0);
        $order = $this->createOrderByRedEnvelope($user_id,$red_envelope['id'],$answer_log_id,$red_envelope['answer_money']);
        $data['number'] = $order['number'];
        $data['answer_log_id'] = $answer_log_id;
        $data['is_pay'] = 0;
        $data['open_id'] = model('User')->where(array('id'=>$user_id))->value('open_id');
        $data['is_need_pay'] = true;
        $data['money'] = $red_envelope['answer_money'];
        return array('status'=>1,'data'=>$data);
    }

    /**
     * 生成红包订单
     * @param $user_id
     * @param $red_envelope_id
     * @param $answer_log_id
     * @param $money
     * @return mixed
     */
    private function createOrderByRedEnvelope($user_id,$red_envelope_id,$answer_log_id,$money){
        $order = $this->makeOrder(Constant::ORDER_TYPE_ANSWER,$red_envelope_id,$money);
        $order['user_id'] = $user_id;
        $order['answer_log_id'] = $answer_log_id;
        $order['pay_type'] = Constant::ORDER_PAY_TYPE_WE_CHAT;
        $order_obj = model('Order')->create($order);
        return $order_obj;
    }

    /**
     * 构造订单
     * @param $order_type
     * @param $red_envelope_id
     * @param $money
     * @return mixed
     */
    private function makeOrder($order_type,$red_envelope_id,$money){
        $order['number'] = build_order_no();
        $order['is_pay'] = 0;
        $order['type'] = $order_type;
        $order['money'] = $money;
        $order['red_envelope_id'] = $red_envelope_id;
        $order['create_time'] = time();
        return $order;
    }

    /**
     * 创建答题记录
     * @param $red_envelope
     * @param $user_id
     * @param $pay_type
     * @param $topic_ids string 题目id
     * @param $is_pay int 是否支付
     * @return mixed
     */
    private function createAnswerLog($red_envelope,$user_id,$pay_type,$topic_ids,$is_pay){
        $data['total_money'] = $red_envelope['money'];
        $data['pay_money'] = $red_envelope['answer_money'];
        $data['topic_num'] = $red_envelope['topic_number'];
        $data['user_id'] = $user_id;
        $data['pay_type'] = $pay_type;
        $data['topic_ids'] = $topic_ids;
        $data['is_pay'] = $is_pay;
        $data['create_time'] = time();
        $data['red_envelope_id'] = $red_envelope['id'];
        $answer_log = model('AnswerLog')->create($data);
//        pclose(popen("php /www/RedEnvelope/public/index.php /index/pay/generateTopicIds/answer_log_id/{$answer_log['id']}/red_envelope_id/{$red_envelope['id']} &", 'r'));
        return $answer_log['id'];
    }

    /**
     * @param $topic_grade string 题目难度
     * @param $topic_num int 题目数量
     * @return string
     */
    public function getRandTopic($topic_grade,$topic_num){
        if($topic_num == 1){
            $grade = [$topic_grade];
        }else{
            $grade = explode(',',$topic_grade);
        }
        $topic_ids = '';
        foreach ($grade as $key=>$value){
            $map['grade'] = $value;
            $topic_id = $this->getRandomTopic($map,$topic_ids);
            if(empty($topic_id)){
                return 0;
            }
            if($key == 0){
                $topic_ids = $topic_id;
            }else{
                $topic_ids .=','.$topic_id;
            }
        }
        return $topic_ids;
    }

    /**
     * 随机获取n条数据
     * @param $map
     * @param $topic_ids
     * @return false|\PDOStatement|string|Collection
     */
    private function getRandomTopic($map,$topic_ids)
    {
        $model = model('Topic');
        $pk = $model->getPK();//获取主键
        $map['is_use'] = 1;
        if(!empty($topic_ids)){
            $topic_id_arr = explode(',',$topic_ids);
            $countcus = $model
                ->where($map)
                ->where('id','not in',$topic_id_arr)
                ->field($pk)->select();//查询数据;
        }else{
            $countcus = $model
                ->where($map)
                ->field($pk)->select();//查询数据;
        }
        $ids = [];
        foreach($countcus as $v=>$val){
            $ids[] = $val[$pk];
        }
        $index = mt_rand(0,count($ids) - 1);
        $query = $ids[$index];
        $topic_id = $model->where($pk,'eq',$query)
            ->value('id');
        return $topic_id;
    }

    /**
     * 根据题目难度随机生成答题记录的题目
     * @param $grade_str string 难度字符串 ,分割
     * @param $topic_num int 需要生成的题目数
     * @return string
     */
    public function getRandomTopicByGrade($grade_str,$topic_num){

        if($topic_num == 1){
            $grade_array = [$grade_str];
        }else{
            $grade_array = explode(',',$grade_str);
        }
        $map['is_use'] = 1;
        $list = Db::name('Topic')
            ->where($map)
            ->field('id,grade')->cache(3600 * 5)->select();//查询数据;
        $topic_list = $this->makeArray();
        foreach ($list as $key=>$value){
            $topic_list[$value['grade']][]=$value['id'];
        }
        $grade_count = [0,0,0,0,0];//每种难度数量
        foreach ($grade_array as $key=>$grade){
            $grade_count[$grade]++;
        }
        $index_array = $this->makeArray();
        foreach ($grade_count as $grade=>$count){//每种难度题目的随机索引
            $index_array[$grade] = $this->unique_rand(0,count($topic_list[$grade])-1,$count);
        }

        $topic_index = [0,0,0,0,0];
        $topic_ids = '';
        foreach ($grade_array as $key=>$grade){
            $index = $index_array[$grade][$topic_index[$grade]];
            $topic_id = $topic_list[$grade][$index];
            if($key == 0){
                $topic_ids = ''.$topic_id;
            }else{
                $topic_ids .= ','.$topic_id;
            }
            $topic_index[$grade]++;
        }

        return $topic_ids;
    }

    private function makeArray(){
        $return_array[0] = [];
        $return_array[1] = [];
        $return_array[2] = [];
        $return_array[3] = [];
        $return_array[4] = [];
        return $return_array;
    }

    /**
     * 随机生成n个范围内的随机数
     * @param $min
     * @param $max
     * @param $num
     * @return array|bool
     */
    private function unique_rand($min, $max, $num) {
        $count = 0;
        $return = array();
        while ($count < $num) {
            $return[] = mt_rand($min, $max);
            $return = array_flip(array_flip($return));
            $count = count($return);
        }
        shuffle($return);
        return $return;
    }

    /**
     * 开始答题 获取题目
     * @param $answer_log_id int 答题记录id
     * @param $user_id int 用户id
     * @return array status
     */
    public function doStartAnswer($answer_log_id,$user_id){
        Db::startTrans();
        try {
            $answer_log = model('AnswerLog')->where(array('id' => $answer_log_id))->find();
            if (!$answer_log) {
                return array('status' => 2, 'msg' => '请勿非法提交');
            }
            if($answer_log['user_id'] != $user_id || $answer_log['is_pay'] != 1 || $answer_log['status'] == Constant::ANSWER_STATUS_END) {
                return array('status' => 2, 'msg' => '对不起，您无法答题！');
            }
            //获取题目
            $topic_ids = explode(',', $answer_log['topic_ids']);
            $right_num = $answer_log['right_num'];
            if ($right_num >= count($topic_ids)) {
                return array('status' => 2, 'msg' => '对不起，您已经答完所有题目！');
            }
            $topic_id = $topic_ids[$right_num];
            if($right_num == 0) {
                model('AnswerLog')->where(array('id' => $answer_log_id))->setField('status', Constant::ANSWER_STATUS_IN);
                Db::commit();
                $this->setStartTime($answer_log_id);
            }
            $this->setAnswerTopicStartTime($answer_log_id,$topic_id);
            $data = $this->getTopic($topic_id);
            return array('status'=>1,'data'=>$data);
        }catch (Exception $e){
            Db::rollback();
            return array('status'=>0,'error'=>$e->getMessage());
        }
    }

    /**
     * 新用户首次答题奖励
     * @param $user_id
     */
    public function rewardAnswer($user_id){
        $map['is_pay'] = 1;
        $map['user_id'] = $user_id;
        $count = model('AnswerLog')->where($map)->count();
        if($count == 0){
            $last_one = model('User')->where(array('id'=>$user_id))->value('last_one');
            if(empty($last_one)){
                return;
            }
            model('User')->where(array('id'=>$last_one))->setInc('answer_money',1);
            model('User')->where(array('id'=>$last_one))->setInc('history_answer_money',1);
            $this->saveMoneyLog($last_one,$user_id);
            $message_logic = new MessageLogic();
            $message_logic->sendMessage($last_one,Constant::CONFIG_NAME_ANSWER_GOLD_REWARD_NOTICE);
        }
    }

    private function saveMoneyLog($user_id,$sub_user_id){
        $current_money = model('User')->where(array('id'=>$user_id))->value('answer_money');
        $logic = new MoneyLogic();
        $money = 1;
        $change_type = Constant::CHANGE_TYPE_NEW_USER;
        $in_out_type = Constant::IN_OUT_TYPE_IN;
        $nickname = model('User')->where(array('id'=>$sub_user_id))->value('nickname');
        $desc = $nickname.'首次答题';
        $money_type = Constant::MONEY_TYPE_CHALLENGE_CARD;
        $logic->saveMoneyLog($money,$current_money,$change_type,
            $in_out_type,$desc,$user_id,$money_type,$sub_user_id);
    }

    /**
     * 获取题目信息 包括选项 没有答案
     * @param $topic_id
     * @return mixed
     */
    public function getTopic($topic_id){
        $data['title'] = model('Topic')->where(array('id'=>$topic_id))->value('title');
        $data['topic_id'] = $topic_id;
        $data['option_list'] = $this->getOptionList($topic_id);
        return $data;
    }

    /**
     * 设置答题开始时间
     * @param $answer_log_id
     */
    private function setStartTime($answer_log_id){
        $redis = new Redis();
        $redis->set('answer_log_start_time_'.$answer_log_id,time());
    }

    /**
     * 获取答题开始时间
     * @param $answer_log_id
     * @return mixed
     */
    private function getStartTime($answer_log_id){
        $redis = new Redis();
        return $redis->get('answer_log_start_time_'.$answer_log_id);
    }

    /**
     * 设置单个题目答题开始时间
     * @param $answer_log_id
     * @param $topic_id
     */
    private function setAnswerTopicStartTime($answer_log_id,$topic_id){
        $redis = new Redis();
        $redis->set('answer_topic_start_time_'.$answer_log_id.'_'.$topic_id,time());
    }

    /**
     * 获取单个题目答题开始时间
     * @param $answer_log_id
     * @param $topic_id
     * @return mixed
     */
    private function getAnswerTopicStartTime($answer_log_id,$topic_id){
        $redis = new Redis();
        return $redis->get('answer_topic_start_time_'.$answer_log_id.'_'.$topic_id);
    }

    /**
     * 检查答案
     * @param $user_id
     * @param $answer_log_id
     * @param $topic_id
     * @param $option_id
     * @return array
     */
    public function checkAnswer($user_id,$answer_log_id,$topic_id,$option_id){
        Db::startTrans();
        try {
            $now = time();
            $answer_log = model('AnswerLog')->where(array('id' => $answer_log_id))->find();
            if (!$answer_log) {
                return array('status' => 2, 'msg' => '请勿非法提交');
            }
            if($answer_log['user_id'] != $user_id || $answer_log['is_pay'] != 1) {
                return array('status' => 2, 'msg' => '对不起，您无法答题！');
            }
            //获取题目
            $topic_ids = explode(',', $answer_log['topic_ids']);
            $right_num = $answer_log['right_num'];
            if (empty($topic_id) || !in_array($topic_id, $topic_ids)) {
                return array('status' => 2, 'msg' => '请勿非法提交！');
            }
            $option_answer_id = model('Topic')->where(array('id' => $topic_id))->value('answer');
            if($answer_log['status'] == Constant::ANSWER_STATUS_END){
                $result['success'] = false;
                $result['is_complete'] = true;
                $result['right_option_id'] = $option_answer_id;
                return array('status'=>1,'data'=>$result);
            }
            if ($right_num >= count($topic_ids)) {
                return array('status' => 2, 'msg' => '对不起，您已经答完所有题目！');
            }

            $success = false;
            if ($option_id == $option_answer_id) {
                $success = true;
                $is_complete = $this->answerRight($now,$answer_log_id,$topic_id,$user_id);
            }else{
                $this->endAnswer($answer_log_id,$topic_id,$user_id,1);
                $is_complete = true;
            }
            $result['success'] = $success;
            $result['is_complete'] = $is_complete;
            $result['right_option_id'] = $option_answer_id;
            Db::commit();
            return array('status'=>1,'data'=>$result);
        }catch (Exception $e){
            Db::rollback();
            Log::write('checkAnswer:'.$e->getMessage());
            return array('status'=>0,'error'=>$e->getMessage());
        }
    }

    /**
     * 答对
     * @param $now int 当前时间
     * @param $answer_log_id
     * @param $topic_id
     * @param $user_id
     * @return bool 是否结束
     */
    private function answerRight($now,$answer_log_id,$topic_id,$user_id){
        //记录答题时间
        $answer_topic_time = $this->getAnswerTopicStartTime($answer_log_id, $topic_id);
        $topic_answer['end_time'] = $now;
        $topic_answer['duration'] = $now - $answer_topic_time;
        $topic_answer['answer'] = $topic_id;
        $topic_answer['is_correct'] = 1;
        $topic_answer['is_answer'] = 1;
        $topic_answer['answer_log_id'] = $answer_log_id;
        $topic_answer['topic_id'] = $topic_id;
        $topic_answer['user_id'] = $user_id;
        model('TopicAnswer')->insert($topic_answer);
        $is_complete = false;
        model('AnswerLog')->where(array('id' => $answer_log_id))->setInc('right_num',1);
        $answer_log = model('AnswerLog')->where(array('id' => $answer_log_id))->field('right_num,topic_num')->find();
        if($answer_log['right_num'] >= $answer_log['topic_num']){
            $is_complete = true;
            //全部答对
            $start_time = $this->getStartTime($answer_log_id);
            $upload_answer_log['end_time'] = $now;
            $upload_answer_log['duration'] = $now - $start_time;
            $upload_answer_log['status'] = Constant::ANSWER_STATUS_END;
            $upload_answer_log['is_all_right'] = 1;//全对
            model('AnswerLog')->where(array('id' => $answer_log_id))->update($upload_answer_log);

            $red_envelope_id = model('AnswerLog')->where(array('id' => $answer_log_id))->value('red_envelope_id');
            model('RedEnvelope')->where(array('id' => $red_envelope_id))
                ->setField('status', Constant::RED_ENVELOPE_STATUS_RECEIVE);//红包被领取
            $this->receiveRedEnvelope($red_envelope_id,$user_id);
        }
       return $is_complete;
    }

    /**
     * 领取红包
     * @param $red_envelope_id int 红包id
     * @param $user_id
     */
    private function receiveRedEnvelope($red_envelope_id,$user_id){
        $red_envelope = model('RedEnvelope')->where(array('id'=>$red_envelope_id))->field('money,user_id')->find();
        $money = $red_envelope['money'];
        model('User')->where(array('id'=>$user_id))->setInc('balance',$money);
        $current_money = model('User')->where(array('id'=>$user_id))->value('balance');
        $logic = new MoneyLogic();
        $change_type = Constant::CHANGE_TYPE_ANSWER_SUCCESS;
        $in_out_type = Constant::IN_OUT_TYPE_IN;
        $desc = '挑战成功，获得奖励！';
        $money_type = Constant::MONEY_TYPE_BALANCE;
        $logic->saveMoneyLog($money,$current_money,$change_type,
            $in_out_type,$desc,$user_id,$money_type,$red_envelope['user_id']);
        //发送红包被领取通知
        $message_logic = new MessageLogic();
        $message_logic->sendMessage($red_envelope['user_id'],Constant::CONFIG_NAME_RED_ENVELOPE_NOTICE);
    }

    /**
     * 答题时间结束自动结算
     * @param $answer_log_id int 答题记录id
     * @param $topic_id int 题目id
     * @param $user_id int 用户id
     */
    public function answerTime($answer_log_id,$topic_id,$user_id){
         Log::write('answerTime');
        ignore_user_abort(); //即使Client断开(如关掉浏览器)，PHP脚本也可以继续执行.
        set_time_limit(0); // 执行时间为无限制，php默认执行时间是30秒，可以让程序无限制的执行下去
        $right_num = model('AnswerLog')->where(array('id'=>$answer_log_id))->value('right_num');
        $interval= 11; // 隔11秒运行
        sleep($interval);
        $answer_log = model('AnswerLog')->where(array('id'=>$answer_log_id))->field('right_num,status')->find();
        if($answer_log['status'] != Constant::ANSWER_STATUS_END && $right_num == $answer_log['right_num']){
            $this->autoEnd($answer_log_id,$topic_id,$user_id);
        }
    }

    /**
     * 长时间未答题自动结束
     * @param $answer_log_id
     * @param $user_id
     */
    public function autoEndAnswer($answer_log_id,$user_id){
        ignore_user_abort();
        set_time_limit(0);
        $topic_num = model('AnswerLog')->where(array('id'=>$answer_log_id))->value('topic_num');
        Log::write('autoEndAnswer');
        $interval= 16 * $topic_num + 45; //时间
        sleep($interval);
        $answer_log = model('AnswerLog')->where(array('id'=>$answer_log_id))->field('right_num,status')->find();
        if($answer_log['status'] != Constant::ANSWER_STATUS_END && $topic_num != $answer_log['right_num']){
            Log::write('autoEndAnswer end');
            $this->autoEnd($answer_log_id,0,$user_id);
        }
    }

    /**
     * 自动结束
     * @param $answer_log_id
     * @param $topic_id
     * @param $user_id
     */
    private function autoEnd($answer_log_id,$topic_id,$user_id){
        Db::startTrans();
        try {
            $this->endAnswer($answer_log_id,$topic_id,$user_id,0);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::write('answerTime:'.$e->getMessage());
        }
    }

    /**
     * 答错结算
     * @param $answer_log_id
     * @param $topic_id
     * @param $user_id
     * @param $is_answer int 是否答题
     */
    private function endAnswer($answer_log_id,$topic_id,$user_id,$is_answer){
        $now = time();
        $answer_topic_start_time = $this->getAnswerTopicStartTime($answer_log_id,$topic_id);
        $start_time = $this->getStartTime($answer_log_id);
        //自动结束
        $upload_answer_log['end_time'] = $now;
        $upload_answer_log['duration'] = $now - $start_time;
        $upload_answer_log['status'] = Constant::ANSWER_STATUS_END;
        model('AnswerLog')->where(array('id' => $answer_log_id))
            ->update($upload_answer_log);

        if(!empty($topic_id)) {
            $topic_answer['end_time'] = $now;
            $topic_answer['duration'] = $now - $answer_topic_start_time;
            $topic_answer['answer'] = 0;
            $topic_answer['is_correct'] = 0;
            $topic_answer['is_answer'] = $is_answer;
            $topic_answer['answer_log_id'] = $answer_log_id;
            $topic_answer['topic_id'] = $topic_id;
            $topic_answer['user_id'] = $user_id;
            model('TopicAnswer')->insert($topic_answer);
        }

        $red_envelope_id = model('AnswerLog')->where(array('id' => $answer_log_id))->value('red_envelope_id');
        model('RedEnvelope')->where(array('id' => $red_envelope_id))
            ->setField('status', Constant::RED_ENVELOPE_STATUS_NO_CHALLENGE);//可答题状态
    }

    /**
     * 答题金进入红包发送者账户
     * @param $red_envelope_id int 红包id
     * @param $source_id int 答题者id
     */
    public function returnMoneyToSender($red_envelope_id,$source_id){
        $red_envelope = model('RedEnvelope')->where(array('id'=>$red_envelope_id))->field('answer_money,user_id')->find();
        $money = $red_envelope['answer_money'];
        $user_id = $red_envelope['user_id'];
        model('User')->where(array('id'=>$user_id))->setInc('balance',$money);
        $current_money = model('User')->where(array('id'=>$user_id))->value('balance');
        $logic = new MoneyLogic();
        $change_type = Constant::CHANGE_TYPE_ANSWER_FAILURE;
        $in_out_type = Constant::IN_OUT_TYPE_IN;
        $desc = '用户答题，获得答题金！';
        $money_type = Constant::MONEY_TYPE_BALANCE;
        $logic->saveMoneyLog($money,$current_money,$change_type,
            $in_out_type,$desc,$user_id,$money_type,$source_id);
    }

    private function getOptionList($topic_id){
        $list = model('Option')
            ->where(array('topic_id'=>$topic_id))
            ->field('is_correct',true)
            ->select();
        return $list;
    }
}